fs = require "fs"

process.on 'uncaughtException',  (err)=>
  console.log err
  fs.writeFileSync('log.txt', err.toString())


require("dotenv").config()

crypto = require('crypto')

code = crypto.createHash "md5"
  .update process.env.FUWUHAOID
  .digest "hex"
  .toUpperCase()

# if process.env.APPKEY is not code
#   return throw new Error('APPKEY不合法')

console.log process.env.MONGODB
koa = require "koa"
path = require "path"
session = require "koa-session-minimal"
MongoStore = require "koa-generic-session-mongo"
render = require "koa-ejs"
serve = require "koa-static"
mount = require "koa-mount"
koaBody = require "koa-body"


fs.mkdirSync 'upload' unless fs.existsSync('upload')

routers = require "./routers"
bot = require "./bot"
schedule = require "./schedule"

app = new koa()
app.proxy = true
app.keys = [process.env.WECHATY_TOEKN]

render app,
  root: path.join __dirname, "views"
  viewExt: "html"
  layout: "layouts/default"
  map: html: "ejs"
  cache: false

app.use(
  koaBody
    multipart: true
    formLimit: "5mb"
    jsonLimit: "5mb"
    textLimit: "5mb"
)
app.use(
  session
    store: new MongoStore {url: process.env.MONGODB, collection: process.env.APPID + "_session"}
)

app.use (ctx, next) ->
  console.log ctx.path

  ctx.state.title = process.env.TITLE or "TITLE 未配置"
  ctx.state.subtitle = ""

  try
    await next()
  catch e
    console.log e
    return (ctx.body = e.message)

app.use serve path.join __dirname, "public"
app.use serve path.join(__dirname, "verify"), maxage: 1000 * 60 * 60 * 24 * 30
app.use mount "/upload", new koa().use serve path.join(__dirname, "upload"), maxage: 1000 * 60 * 60 * 24 * 30

app.use mount "/qrs", new koa().use serve path.join(__dirname, "qrs"), maxage: 1000 * 60 * 60 * 24 * 30

app.use routers.routes()

app.on "error", console.log


    # schedule.start()
app.listen process.env.PORT, (err) ->


  console.log err if err
  console.log process.env.APPID + " start listen port " + process.env.PORT


  Wechaty  = require "wechaty"
  {PuppetXp} = require "wechaty-puppet-xp"
  axios  = require "axios"
  puppet = new PuppetXp()
  {WechatyBuilder} = Wechaty
  try
    instance = WechatyBuilder.build(
      puppet: puppet
      name: 'bot'
    )
    instance.on('error', console.error)
    await bot
      .load instance

    console.log '运行成功' + puppet.version()

  catch err
    console.log err

